local config = require("config")
local luasql = require("luasql.sqlite3")

local env = luasql.sqlite3()

local method = {}
local mt = {__index = method}

function method:escape(sql)	return self.conn:escape(sql) end
function method:close() self.conn:close() self.conn = nil end
function method:execute(sql) return self.conn:execute(sql) end

function method:select(sql)
	local cur, err = self.conn:execute(sql)
	if not cur then
		return nil, err
	end

	local arr = {}
	local row = cur:fetch({}, "a")
	while row do
		table.insert(arr, row)
		row, err = cur:fetch({}, "a")	-- reusing the table of results
		if err then
			return nil, err
		end
	end
	cur:close()

	return arr
end

function method:connect()
	local cfg = config:ins()
	local work_dir = cfg:work_dir()
	local disk_m, memo_m = work_dir .. "/disk_m.db", work_dir .. "/memo_m.db"
	local conn, e = env:connect(disk_m) 	assert(conn, e)
	local sql = string.format("attach database '%s' as '%s'", memo_m, "memo")
	local r, e = conn:execute(sql) 			assert(r, e)
	local params = {"PRAGMA journal_mode=memory", "PRAGMA auto_vacuum=FULL"}
	for _, sql in ipairs(params) do
		local r, e = conn:execute(sql) 		assert(r, e)
	end
	self.conn = conn
	return true
end

local function new()
	local obj = {conn = nil}
	setmetatable(obj, mt)
	return obj
end

return {new = new}
